package academic.ui.client.widgets;

import java.util.Date;

import ui.client.GenericContainerTag;
import ui.client.GenericTextInput;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.Composite;

public class DateTimePicker extends Composite {

	private GenericContainerTag div = new GenericContainerTag("div");
	
	private static String START_DATE_ID="dt_date_start";
	private static String START_TIME_ID="dt_time_start";
	private static String END_DATE_ID="dt_date_end";
	private static String END_TIME_ID="dt_time_end";
	
	public DateTimePicker() {
		//create tags
		GenericContainerTag p = new GenericContainerTag("p");
		GenericContainerTag strong = new GenericContainerTag("strong","from:");
		GenericTextInput dateStart = new GenericTextInput("");
		dateStart.getElement().setId(START_DATE_ID);
		GenericTextInput timeStart = new GenericTextInput("");
		timeStart.getElement().setId(START_TIME_ID);
		GenericContainerTag p2 = new GenericContainerTag("p");
		GenericContainerTag strong2 = new GenericContainerTag("strong","to:");
		GenericTextInput dateEnd = new GenericTextInput("");
		dateEnd.getElement().setId(END_DATE_ID);
		GenericTextInput timeEnd = new GenericTextInput("");
		timeEnd.getElement().setId(END_TIME_ID);
		GenericContainerTag script = new GenericContainerTag("script");
		
		script.getElement().setInnerHTML("$(function() {$('#"+START_DATE_ID+",#"+START_TIME_ID+",#"+END_DATE_ID+",#"+END_TIME_ID+"').calendricalDateTimeRange();});");
		//structure tags
		p.add(strong);
		p.add(dateStart);
		p.add(timeStart);
		p2.add(strong2);
		p2.add(dateEnd);
		p2.add(timeEnd);
		div.add(p);
		div.add(p2);
		div.add(script);
		initWidget(div);
	}
	
	private native String getStartDate() /*-{
	return $wnd.$('#'+@academic.ui.client.widgets.DateTimePicker::START_DATE_ID).val();
	}-*/; 

	private native String getStartTime() /*-{
		return $wnd.$('#'+@academic.ui.client.widgets.DateTimePicker::START_TIME_ID).val();
	}-*/;
	
	private native String getEndDate() /*-{
	return $wnd.$('#'+@academic.ui.client.widgets.DateTimePicker::END_DATE_ID).val();
	}-*/; 

	private native String getEndTime() /*-{
		return $wnd.$('#'+@academic.ui.client.widgets.DateTimePicker::END_TIME_ID).val();
	}-*/;
	
	public Date getStartDateTime() {
		DateTimeFormat dtf = DateTimeFormat.getFormat("dd/MM/yyyy h:mma");
		return dtf.parse(getStartDate()+" "+getStartTime());
	}
	
	public Date getEndDateTime() {
		DateTimeFormat dtf = DateTimeFormat.getFormat("dd/MM/yyyy h:mma");
		return dtf.parse(getEndDate()+" "+getEndTime());
	}
}
